package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CharsetConstant;
import com.lehecai.core.util.CoreFetcherUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 彩乐乐 开奖结果抓取
 * @author Sunshow
 *
 */
public class LotteryDrawFetchWorkerGXFC extends AbstractLotteryDrawFetchWorker {

    private static final Map<LotteryType, String> lotteryTypeMap = new HashMap<LotteryType, String>();

    private static final String URL_DEFAULT = "http://www.gxcaipiao.com.cn:8090/gxcams/xml/award_%s.xml";

    static {
        lotteryTypeMap.put(LotteryType.GXKL10, "09");
    }

	public LotteryDrawFetchWorkerGXFC(LotteryType lotteryType){
		super(lotteryType);
	}
	
	@Override
	public LotteryDraw fetchResult(String phase) {
        return this.fetchResultDetail(phase);
    }

	@Override
    @SuppressWarnings("unchecked")
	public LotteryDraw fetchResultDetail(String phase) {
        LotteryType lotteryType = this.getLotteryType();

        String fetchUrl = this.getResultDetailUrl(phase);
        if (StringUtils.isEmpty(fetchUrl)) {
            logger.error("==详细页面==抓取=={}==期号：{}==详细地址不存在，返回null", lotteryType.getName(), phase);
            return null;
        }

        Map<String, String> headerParams = new HashMap<String, String>();
        headerParams.put("Referer", "http://www.gxcaipiao.com.cn:8090/gxcams/klsfnt.jsp");
        headerParams.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11");

        String data = CoreFetcherUtils.URLGetWithHeaderParams(fetchUrl, headerParams, null, CharsetConstant.CHARSET_GBK);

        if (StringUtils.isEmpty(data)) {
            logger.error("data is null or 404 Not Found, url={}", fetchUrl);
            return null;
        }

        Document document;
        try {
            document = DocumentHelper.parseText(data);
        } catch (DocumentException e) {
            logger.error("解析xml错误, data={}", data);
            logger.error(e.getMessage(), e);
            return null;
        }

        Element rootElement = document.getRootElement();
        List<Element> phaseElementList = rootElement.elements("p");

        for (Element phaseElement : phaseElementList) {
            String fetchedPhase = phaseElement.attributeValue("id");
            if (fetchedPhase == null) {
                continue;
            }
            if (phase != null && !phase.equals(fetchedPhase)) {
                continue;
            }

            LotteryDraw lotteryDraw = new LotteryDraw();
            lotteryDraw.setLotteryType(lotteryType);
            lotteryDraw.setPhase(fetchedPhase);

            lotteryDraw.setTimeDraw(phaseElement.attributeValue("t"));

            String[] nums = StringUtils.split(phaseElement.attributeValue("c"), ",");
            List<String> formatNums = new ArrayList<String>();
            for (String num : nums) {
                formatNums.add(StringUtils.leftPad(num, 2, '0'));
            }
            lotteryDraw.setResult(StringUtils.join(formatNums, ","));

            return lotteryDraw;
        }

        return null;
	}

	@Override
	protected String getResultDetailUrl(String phase) {
        LotteryType lotteryType = this.getLotteryType();

        if (!lotteryTypeMap.containsKey(lotteryType)) {
            return null;
        }

        String lotteryTypeExternal = lotteryTypeMap.get(lotteryType);

        return String.format(URL_DEFAULT, lotteryTypeExternal);
    }

	@Override
	protected String getResultUrl(String phase) {
		return null;
	}
}
